// Add new user to the system in "manage user" tab.
function addNewUser() {
    // Get the data from all the fields
    var username = $('input[name=username]');
    var pwd = $('input[name=password]');
    var fName = $('input[name=fName]');
    var lName = $('input[name=lName]');
    var type = $('select[name=cType] option:selected');
    var siteID = $('select[name=siteId] option:selected');

    // Simple validation to make sure user entered something
    // If error found, add highlight class to the text field
	
    if (
	// Generate error message if username field is empty.
	ValidateInputBox('username', 'musername') &&
    
    // Generate error message password field is empty.v
	ValidateInputBox('password', 'mpwd') &&
    
    // Generate error message if first name field is empty.
	ValidateInputBox('fName', 'mfName') &&
    
    // Generate error message if last name field is empty.
	ValidateInputBox('lName', 'mlName') &&
    
    // Generate error message if the default type is selected.
	ValidateDropBox('cType', 'mtype') &&
    
    // Generate error message if the default siteID is selected.
	ValidateDropBox('siteId', 'mSiteID')
    )
	{
        // organize the data properly
        var data = 'fName=' + fName.val() + '&lName=' + lName.val()
                + '&username=' + username.val() + '&password=' + pwd.val()
                + '&cType=' + type.val() + '&siteID=' + siteID.val();

        // start the ajax

        $
                .ajax({
                    url : "/add/user",
                    type : "POST",
                    data : data,
                    cache : false,

                    success : function() {

                        // dsplay success message.
                        document.getElementById('mUserAddMessage').innerHTML = "Add User Successfully.";
                        // hide the form
                        $('#addUserForm').fadeOut('slow');
                        document.getElementById('addUserLink').innerHTML = '<img src="img/details_open.png" alt"Add Shipment"/>Click Here to Add New Shipment.';
						document.getElementById('mUserAddMessage').className = 'hiddenMessage';

                        // Add entry to datatable

                        $('#userTable').dataTable().fnAddData(
                                [username.val(), fName.val(), lName.val(), type.text(),
										siteID.text()]);
										
						// reset user add form.
						document.getElementById('addUser').reset();
                    },

                    failure : function() {
                    },
                    error : function() {
                        alert('Sorry, unexpected error. Please try again later.');
                    }
                });
    } else {
        document.getElementById('mUserAddMessage').innerHTML = "Please verify your Inputs.";
        document.getElementById('mUserAddMessage').className = 'err';
    }

}

// Add a "step" to the checklist. Each step is an event within a checklist.
function addStep() {

	var checklist = $('textarea[name=checkList]');
    var stepD = $('textarea[name=stepD]');


    // Generate error if the step description is an emtpy string.
	
	if (
	ValidateTextareaBox('stepD', 'mStepDescription'))
	{
		
		$('span[id=addStepPass]').removeClass('hiddenMessage');
        $('span[id=addStepFail]').addClass('hiddenMessage');

        // Generate JSON aray to be sent to server for the checklist
        // description.
        if (checklist.val() === "") {
            checklist.val("[\"" + stepD.val() + "\"]");
        } else {
            var newString = checklist.val().substring(0,
                    checklist.val().length - 1);
            newString += ", \"" + stepD.val() + "\"]";
            checklist.val(newString);
        }
        $('#stepsTable').removeClass('hiddenTable');
        $('#stepsTable').dataTable().fnAddData([ stepD.val() ]);
        stepD.val('');
    }
	else {
		$('span[id=addStepPass]').addClass('hiddenMessage');
        $('span[id=addStepFail]').removeClass('hiddenMessage');
	}

}

// Add Checklist to the system.
function addNewCheckList() {
    // Get the data from all the fields
    var listName = $('select[name=clName] option:selected');
    var mlistName = $('span[id=mListName]');
    var checkList = $('textarea[name=checkList]');
    var mCheckListPass = $('span[id=mCheckListPass]');
    var mCheckListFail = $('span[id=mCheckListFail]');
    var minStepErr = $('span[id=minStepErr]');
	
	//Convert String to JavaScript Array.
	var checklistArray = checkList.val().substring(1,checkList.val().length - 1).split(',');
	
	
	var postSite;
	if (listName.val() == 0) {
		postSite="/change/startingChecklist"
	}
	else {
		postSite="/change/endingChecklist"
	}
	

    // Simple validation to make sure user entered something
    // If error found, add highlight class to the text field

	if (
    // Generate error message if name of the checklist is default.
	ValidateDropBox('clName', 'mlistName') &&
    

    // Generate error message if checklist is empty with events.
	ValidateTextareaBox('checkList', 'minStepErr'))
    {

        // organize the data properly
        var data = 'checklist='
                + checkList.val();

        // start the ajax

        $
                .ajax({
                    url : postSite,
                    type : "POST",
                    data : data, // pass the data
                    cache : false,

                    success : function() {
                        mCheckListPass.removeClass('hiddenMessage');
                        mCheckListFail.addClass('hiddenMessage');
                        // hide the form

                        $('#addCheckListForm').fadeOut('slow');

                        
						// Clear Destination Point Table
						$('#stepsTable').dataTable().fnClearTable();

                        // Add entry to datatable
						if (listName.val() == 0) {
							for (i = 0; i < checklistArray.length; i++) {
                        $('#sCheckListTable').dataTable().fnAddData(
                                [checklistArray[i]]);
							}
						}
						else {
							for (i = 0; i < checklistArray.length; i++) {
                        $('#eCheckListTable').dataTable().fnAddData(
                                [ checklistArray[i]]);
							}
						}
						// Clear form
                        document.getElementById('addCheckList').reset();
                    },

                    failure : function() {
                        mCheckListFail.removeClass('hiddenMessage');
                        mCheckListPass.addClass('hiddenMessage');
                    },
                    error : function() {
                        alert('Sorry, unexpected error. Please try again later.');
                        mCheckListFail.removeClass('hiddenMessage');
                        mCheckListPass.addClass('hiddenMessage');
                    }
                });
    } else {
        mCheckListFail.removeClass('hiddenMessage');
        mCheckListPass.addClass('hiddenMessage');

    }

}

// Route Manage code
// Add destination point to route.
function addPoint() {
    var points = $('textarea[name=points]');
	var pointsText = $('textarea[name=pointsText]');
    var pointD = $('select[name=pointD] option:selected');
	
	if (
	//Verify if a valid Description has been entered
	ValidateDropBox('pointD', 'mPointDescription'))
	{
		$('span[id=addPointPass]').removeClass('hiddenMessage');
        $('span[id=addPointFail]').addClass('hiddenMessage');
        if (points.val() === "") {
            points.val("[\"" + pointD.val() + "\"]");
        } else {
            var newString = points.val().substring(0, points.val().length - 1);
            newString += ", \"" + pointD.val() + "\"]";
            points.val(newString);
        }
		if (pointsText.val() === "") {
            pointsText.val("[\"" + pointD.text() + "\"]");
        } else {
            var newString = pointsText.val().substring(0, pointsText.val().length - 1);
            newString += ", \"" + pointD.text() + "\"]";
            pointsText.val(newString);
        }
        $('#pointsTable').removeClass('hiddenTable');
        $('#pointsTable').dataTable().fnAddData([ pointD.text() ]);
 
    }
	else {
		$('span[id=addPointPass]').addClass('hiddenMessage');
        $('span[id=addPointFail]').removeClass('hiddenMessage');
	}

}

// Add Route to the system.
function addNewRoute() {
    // Get the data from all the fields
    var rName = $('select[name=rName] option:selected');
    var points = $('textarea[name=points]');
	var pointsText = $('textarea[name=pointsText]');
    var mRoutePass = $('span[id=mRoutePass]');
    var mRouteFail = $('span[id=mRouteFail]');
    var minPointErr = $('span[id=minPointErr]');

	//Convert String to JavaScript Array.
	var pointsArray = pointsText.val().substring(1,pointsText.val().length - 1).split(',');
	
	//Generate a formated string to be added to the table.
	var tablePointsString = '<ol>';
	for (i = 0; i < pointsArray.length; i++)
	{
		tablePointsString += '<li>'+pointsArray[i]+'</li>';
	}
	tablePointsString += '</ol>';

    // Simple validation to make sure user entered something
	if (
    // If error found, add highlight class to the text field
	ValidateDropBox('rName', 'mRName') &&
	ValidateTextareaBox('points', 'minPointErr'))
    {

        // organize the data properly
        var data = 'routeName=' + rName.val() +  '&routeDestinations='
                + points.val();

        // start the ajax

        $
                .ajax({
                    url : "/add/route",
                    type : "POST",
                    data : data, // pass the data
                    cache : false,

                    // Function called when AJAX return a success.
                    success : function() {
                        mRoutePass.removeClass('hiddenMessage');
                        mRouteFail.addClass('hiddenMessage');
                        // hide the form

                        $('#addRouteForm').fadeOut('slow');
						// Clear Destination Point Table
						$('#pointsTable').dataTable().fnClearTable();
                        // Add entry to datatable
                        $('#routeTable').dataTable().fnAddData(
                                [ rName.text(), tablePointsString ]);
										
						// Clear form
                        document.getElementById('addRoute').reset();
						document.getElementById('addRouteLink').innerHTML = '<img src="img/details_open.png" alt="Expand"/>Add New Route';
                    },
                    // function to be called when AJAX return a failure.
                    failure : function() {
                        mRouteFail.removeClass('hiddenMessage');
                        mRoutePass.addClass('hiddenMessage');
                    },
                    // function to be called when AJAX return an error.
                    error : function() {
                        alert('Sorry, unexpected error. Please try again later.');
                        mRouteFail.removeClass('hiddenMessage');
                        mRoutePass.addClass('hiddenMessage');
                    }
                });
    } else {
        mRouteFail.removeClass('hiddenMessage');
        mRoutePass.addClass('hiddenMessage');

    }

}

// Add Instruction Step to Client Hospital Checklist
function addInstStep() {
    var instList = $('textarea[name=instList]');
    var instItem = $('textarea[name=instItem]');
	
	if (
	//Verify if a valid Description has been entered
	ValidateTextareaBox('instItem', 'mInstItem'))
	{
		//Display Success message
		$('span[id=addInstItemPass]').removeClass('hiddenMessage');
		
		//Generate JSON Array String
        if (instList.val() === "") {
            instList.val("[\"" + instItem.val() + "\"]");
        } else {
            var newString = instList.val().substring(0, instList.val().length - 1);
            newString += ", \"" + instItem.val() + "\"]";
            instList.val(newString);
        }
		//Add Entry to the table
        $('#instTable').removeClass('hiddenTable');
        $('#instTable').dataTable().fnAddData([ instItem.val() ]);
		
		//Reset instItem Value.
		instItem.val("");
 
    }
	else {
		$('span[id=addInstItemPass]').addClass('hiddenMessage');

	}

}
//Add Hospitalto the System.
function addNewHospital() {
	//Data
	var hName = $('input[name=hName]');
	var hAddress = $('input[name=hAddress]');

	if ( ValidateInputBox('hName', 'mHName') &&
		ValidateInputBox('hAddress', 'mHAddress'));
	{
		var data = 'hName=' + hName.val()
		+ '&hAddress=' + hAddress.val();
		
		$.ajax({
			url : "/add/hospital",
			type : "POST",
			data : data,
			cache : false,
			
			//Function called when AJAX return a success.
			success : function() {
				$('span[id=addHospitalPass]').removeClass('hiddenMessage');
				$('span[id=addHospitalFail]').addClass('hiddenMessage');

				//TODO: Update table to reflect the changes
				// Add entry to datatable
                        $('#hospitalTable')
                                .dataTable()
                                .fnAddData(
                                        [
                                                
                                         hName.val(),
                                         hAddress.val()
                                         ]);
										 
					document.getElementById('addHospital').reset();
				
			},
			// Function to be called when AJAX return a failure.
			failure : function() {
				$('span[id=addHospitalPass]').addClass('hiddenMessage');
				$('span[id=addHospitalFail]').removeClass('hiddenMessage');
			},
			
			error : function() {
				$('span[id=addHospitalPass]').addClass('hiddenMessage');
				$('span[id=addHospitalFail]').removeClass('hiddenMessage');
			}
		});
			
	}
	
}

//Add ClientSite to the System.
function addNewClientSite() {
	//Data
	var siteName = $('input[name=siteName]');
	var hID = $('select[name=hID] option:selected');
	var hPhone = $('input[name=hPhone]');
	var instList = $('textarea[name=instList]');
	
	//Convert String to JavaScript Array.
	var instArray = instList.val().substring(1,instList.val().length - 1).split(',');
	
	//Generate a formated string to be added to the table.
	var tableInstString = '<ol>';
	for (i = 0; i < instArray.length; i++)
	{
		tableInstString += '<li>'+instArray[i]+'</li>';
	}
	tableInstString += '</ol>';
	
	
	if ( ValidateInputBox('siteName', 'mSiteName') &&
		ValidateDropBox('hID', 'mHID') &&
		ValidateInputBox('hPhone', 'mHPhone') &&
		ValidateTextareaBox('instList', 'mInstList'));
	{
		var data = 'siteName=' + siteName.val()
		+ '&hID=' + hID.val() +'&hPhone=' + hPhone.val()
		+'&instList='+instList.val();
		
		$.ajax({
			url : "/add/clientsite",
			type : "POST",
			data : data,
			cache : false,
			
			//Function called when AJAX return a success.
			success : function() {
				$('span[id=addClientSitePass]').removeClass('hiddenMessage');
				$('span[id=addClientSiteFail]').addClass('hiddenMessage');
				
				// Add entry to datatable
                        $('#clientSiteTable').dataTable().fnAddData(
                                [ siteName.val(),
                                        hID.text(), hPhone.val(), tableInstString]);
						//reset add clientsite form.
						document.getElementById('addClientSite').reset();
						$('#instTable').dataTable().fnClearTable();
				
				// Removie InstructionTemPass success
				$('span[id=addInstItemPass]').addClass('hiddenMessage');
				document.getElementById('addCheckListLink').innerHTML = '<img src="img/details_open.png" alt="Expand"/>Add New Checklist';
			},
			// Function to be called when AJAX return a failure.
			failure : function() {
				$('span[id=addClientSitePass]').addClass('hiddenMessage');
				$('span[id=addClientSiteFail]').removeClass('hiddenMessage');
			},
			
			error : function() {
				$('span[id=addClientSitePass]').addClass('hiddenMessage');
				$('span[id=addClientSiteFail]').removeClass('hiddenMessage');
			}
		});
			
	}
	
}
